package com.yxw.yxnet_cd_center.customer_service.service.impl;



//import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
//import org.springframework.http.server.reactive.ServerHttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yxw.yxnet_cd_center.customer_service.entity.YxcscClientFiledServiceEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxcscMqttServersClientEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxcscServiceTalkRecordEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsProblemLibEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsChannelEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsPortEntity;
import com.yxw.yxnet_cd_center.customer_service.dto.ClientFiledServiceDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.SubscribeTopicResultDTO;
import com.yxw.yxnet_cd_center.customer_service.mapper.YxcscClientFiledServiceMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.YxcscMqttServersClientMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.YxcscServiceTalkRecordMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.UserMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.PrcMapper;
import com.yxw.yxnet_cd_center.customer_service.service.IYxcscClientFiledServiceService;
import com.yxw.yxnet_cd_center.common.utils.BaseResult;
import com.yxw.yxnet_cd_center.customer_service.dto.ClientFiledDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.ClientSendTalkDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.ClientScoreDTO;
import com.yxw.yxnet_cd_center.customer_service.service.ICacheService;
import com.yxw.yxnet_cd_center.customer_service.vo.MqttServerInfor2AndroidVO;
import com.yxw.yxnet_cd_center.customer_service.vo.MqttServersListenerTypeVO;
import com.yxw.yxnet_cd_center.common.constant.MqttPrefixConstant;
import javax.servlet.http.HttpServletRequest;
import cn.hutool.core.util.StrUtil;
import com.yxw.yxnet_cd_center.customer_service.dto.ClientHelpDocuListDTO;
import com.yxw.yxnet_cd_center.customer_service.entity.YxcscCustomerAccessServiceEntity;
import com.yxw.yxnet_cd_center.customer_service.mapper.YxcscCustomerAccessServiceMapper;
import com.yxw.yxnet_cd_center.customer_service.utils.Aes128;
import com.yxw.yxnet_cd_center.customer_service.service.IMsgProcessService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yxw.yxnet_cd_center.customer_service.dto.ClientHelpDocuDTO;
import com.yxw.yxnet_cd_center.customer_service.entity.FlowRuleUserEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsUserEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxcscBaseChannelUserEntity;
import com.yxw.yxnet_cd_center.customer_service.mapper.FlowRuleUserMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.YxcscBaseChannelUserMapper;
import com.yxw.yxnet_cd_center.customer_service.utils.ErrorLog;
import com.yxw.yxnet_cd_center.customer_service.vo.MemberVo;
/*

import com.yxw.customer_service_center.customer_service.entity.YxCsUserWorkEntity;
import com.yxw.customer_service_center.customer_service.service.UserWorkService;
import com.yxw.customer_service_center.customer_service.vo.SessionIdVO;
import javax.crypto.NoSuchPaddingException;
import java.security.NoSuchAlgorithmException;
import com.yxw.customer_service_center.customer_service.mapper.UserWorkMapper;
import com.yxw.customer_service_center.customer_service.vo.MqttInforCustomerVO;
import com.yxw.customer_service_center.customer_service.utils.RedisManager;
import com.yxw.customer_service_center.customer_service.dto.CustomerRequestServiceDTO;
import com.yxw.customer_service_center.customer_service.dto.YxcscServiceTalkRecordDTO;
import com.yxw.customer_service_center.customer_service.dto.YxcscClientFiledServiceDTO;
import com.yxw.yxnet_cd_center.common.constant.RedisIdConstant;
import com.yxw.yxnet_cd_center.common.enums.ContentTypeEnum;


*/

/**
 * 客户会话所有处理
 * @author hjx
 * @date 2023.09.22
 */
@Slf4j
@Service
//public class YxcscClientFiledServiceServiceImpl  extends ServiceImpl<YxcscClientFiledServiceMapper, YxcscClientFiledServiceEntity> implements IYxcscClientFiledServiceService{
public class YxcscClientFiledServiceServiceImpl  implements IYxcscClientFiledServiceService{
    @Autowired
    private YxcscCustomerAccessServiceMapper oYxcscCustomerAccessServiceMapper;    
    @Autowired
    private YxcscClientFiledServiceMapper oYxcscClientFiledServiceMapper;
    @Autowired
    private YxcscMqttServersClientMapper oYxcscMqttServersClientMapper;
    @Autowired
    private YxcscServiceTalkRecordMapper oYxcscServiceTalkRecordMapper;
    @Autowired
    private PrcMapper oPrcMapper;
    @Autowired
    private IMsgProcessService oIMqttProcessService;    
    
    @Autowired
    private UserMapper oUserMapper;
    
    @Autowired
    private ICacheService oICacheService;
    
    @Autowired
    private FlowRuleUserMapper oFlowRuleUserMapper;    
    
    @Autowired
    private YxcscBaseChannelUserMapper oYxcscBaseChannelUserMapper;    
    /*** 
    * 获取Mqtt服务器信息
    * @param userId
    * @return MqttServerInforVO
    **/
    @Override
    public BaseResult getMqttInfoNotSafe(ClientFiledDTO oClientFiledDTO)
    {
        QueryWrapper<YxcscMqttServersClientEntity> oYxcscMqttServersClientQueryWrapper = new QueryWrapper();
        oYxcscMqttServersClientQueryWrapper.eq("channel_code",oClientFiledDTO.getChannelCode()).orderByAsc("host");
        List<YxcscMqttServersClientEntity> oListYxcscMqttServersClient = oYxcscMqttServersClientMapper.selectList(oYxcscMqttServersClientQueryWrapper);
        MqttServerInfor2AndroidVO oMqttServerInfor2AndroidVO = null;
        ArrayList<MqttServersListenerTypeVO> listener = null; 
        String host = "";        
        if(!oListYxcscMqttServersClient.isEmpty())
        { 
            for(YxcscMqttServersClientEntity oYxcscMqttServersClientEntity : oListYxcscMqttServersClient)
            {
                if(!host.equals(oYxcscMqttServersClientEntity.getHost()))
                {
                    //log.info("host=" + host);
                    //log.info("oYxcscMqttServersClientEntity.getHost() = " + oYxcscMqttServersClientEntity.getHost());
                    //log.info("oMqttServerInfor2AndroidVO = new MqttServerInfor2AndroidVO();");
                    oMqttServerInfor2AndroidVO = new MqttServerInfor2AndroidVO();
                    oMqttServerInfor2AndroidVO.setHostURL(oYxcscMqttServersClientEntity.getHost());
                    oMqttServerInfor2AndroidVO.setUserName(oYxcscMqttServersClientEntity.getUser());
                    oMqttServerInfor2AndroidVO.setPassWord(oYxcscMqttServersClientEntity.getPwd());
                    oMqttServerInfor2AndroidVO.setClientId(oClientFiledDTO.getChannelCode() + "_" + oClientFiledDTO.getUserId() + "_" + java.util.UUID.randomUUID().toString().replaceAll("-", ""));
                    if(null != listener)
                    {
                        oMqttServerInfor2AndroidVO.setListener(listener);
                    }
                    //log.info("listener = new ArrayList();");
                    listener = new ArrayList();
                    host = oYxcscMqttServersClientEntity.getHost();
                }
                MqttServersListenerTypeVO oMqttServersListenerTypeVO = new MqttServersListenerTypeVO();                
                oMqttServersListenerTypeVO.setType(oYxcscMqttServersClientEntity.getType());
                oMqttServersListenerTypeVO.setPort(oYxcscMqttServersClientEntity.getPort().toString());                
                listener.add(oMqttServersListenerTypeVO);
            }
            oMqttServerInfor2AndroidVO.setListener(listener);            
            return BaseResult.success(oMqttServerInfor2AndroidVO);
        }
        else
        {
            return BaseResult.failed("还没有配置MQTT服务器参数");
        }
    }
    /*** 
    * 获取Mqtt服务器信息
    * @param userId
    * @return MqttServerInforVO
    **/
    @Override
    public BaseResult getMqttInfo(HttpServletRequest httpRequest,ClientFiledDTO oClientFiledDTO)
    {
        /*
        ServerHttpRequest httpRequest
        List<String> tokens  = httpRequest.getHeaders().get("token");
        String token = null;
        if(!tokens.isEmpty())
        {
            token = tokens.get(0).trim().substring(0, 16);            
        }
        else
        {
            return BaseResult.failed("没有获取到token");
        }
        */
        String token = httpRequest.getHeader("token");
        if(StrUtil.isBlank(token))
        {
            return BaseResult.failed("没有获取到token");
        }
        else
        {
            token = token.substring(0, 16);
        }
        log.info("token=" + token);
        QueryWrapper<YxcscMqttServersClientEntity> oYxcscMqttServersClientQueryWrapper = new QueryWrapper();
        oYxcscMqttServersClientQueryWrapper.eq("channel_code",oClientFiledDTO.getChannelCode()).orderByAsc("host");
        List<YxcscMqttServersClientEntity> oListYxcscMqttServersClient = oYxcscMqttServersClientMapper.selectList(oYxcscMqttServersClientQueryWrapper);
        MqttServerInfor2AndroidVO oMqttServerInfor2AndroidVO = null;
        ArrayList<MqttServersListenerTypeVO> listener = null; 
        String host = "";        
        if(!oListYxcscMqttServersClient.isEmpty())
        { 
            for(YxcscMqttServersClientEntity oYxcscMqttServersClientEntity : oListYxcscMqttServersClient)
            {
                if(!host.equals(oYxcscMqttServersClientEntity.getHost()))
                {
                    //log.info("host=" + host);
                    //log.info("oYxcscMqttServersClientEntity.getHost() = " + oYxcscMqttServersClientEntity.getHost());
                    //log.info("oMqttServerInfor2AndroidVO = new MqttServerInfor2AndroidVO();");
                    oMqttServerInfor2AndroidVO = new MqttServerInfor2AndroidVO();
                    oMqttServerInfor2AndroidVO.setHostURL(oYxcscMqttServersClientEntity.getHost());
                    oMqttServerInfor2AndroidVO.setUserName(oYxcscMqttServersClientEntity.getUser());
                    oMqttServerInfor2AndroidVO.setPassWord(oYxcscMqttServersClientEntity.getPwd());
                    oMqttServerInfor2AndroidVO.setClientId(oClientFiledDTO.getChannelCode() + "_" + oClientFiledDTO.getUserId() + "_" + java.util.UUID.randomUUID().toString().replaceAll("-", ""));
                    if(null != listener)
                    {
                        oMqttServerInfor2AndroidVO.setListener(listener);
                    }
                    //log.info("listener = new ArrayList();");
                    listener = new ArrayList();
                    host = oYxcscMqttServersClientEntity.getHost();
                }
                MqttServersListenerTypeVO oMqttServersListenerTypeVO = new MqttServersListenerTypeVO();                
                oMqttServersListenerTypeVO.setType(oYxcscMqttServersClientEntity.getType());
                oMqttServersListenerTypeVO.setPort(oYxcscMqttServersClientEntity.getPort().toString());                
                listener.add(oMqttServersListenerTypeVO);
            }
            oMqttServerInfor2AndroidVO.setListener(listener);
            JSONObject oJSONObject = (JSONObject)JSON.toJSON(oMqttServerInfor2AndroidVO);
            String cMatter = oJSONObject.toString();
            cMatter = Aes128.Aes128EncryptUtf8(token, cMatter).getData().toString();
            //log.info("getMqttInfo->cMatter=" + cMatter);
            return BaseResult.success(cMatter);
        }
        else
        {
            return BaseResult.failed("还没有配置MQTT服务器参数");
        }
    }    
    /*** 
    * 客户申请服务后
    * @param oYxcscClientFiledServiceDTO
    * @return Integer
    **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult filedService(ClientFiledServiceDTO oClientFiledServiceDTO)
    {
        if(!oClientFiledServiceDTO.getServiceType().equals("consulting") && !oClientFiledServiceDTO.getServiceType().equals("complaint"))
        {
            return BaseResult.failed("serviceType 只能是 'consulting' 或 'complaint'");
        }
        YxCsChannelEntity oYxCsChannelEntity = oICacheService.getChannelInfor(oClientFiledServiceDTO.getChannelCode());
        YxCsPortEntity oYxCsPortEntity  = oICacheService.getPortInfor(oClientFiledServiceDTO.getPortCode());
        if(null== oYxCsChannelEntity)
        {
            return BaseResult.failed("找不到对应渠道");
        }
        if(null== oYxCsPortEntity)
        {
            return BaseResult.failed("找不到对应端口");
        }
        if(ObjectUtil.isNotEmpty( oClientFiledServiceDTO.getOrderId()))
        {
            oClientFiledServiceDTO.setOrderId(oClientFiledServiceDTO.getOrderId().trim());
        }
        if(ObjectUtil.isNotEmpty( oClientFiledServiceDTO.getOrderState()))
        {
            oClientFiledServiceDTO.setOrderState(oClientFiledServiceDTO.getOrderState().trim());
        }
        if(ObjectUtil.isNotEmpty( oClientFiledServiceDTO.getProductId()))
        {
            oClientFiledServiceDTO.setProductId(oClientFiledServiceDTO.getProductId().trim());
        }
        if(ObjectUtil.isNotEmpty( oClientFiledServiceDTO.getProductType()))
        {
            oClientFiledServiceDTO.setProductType(oClientFiledServiceDTO.getProductType().trim());
        }
        if(ObjectUtil.isNotEmpty( oClientFiledServiceDTO.getEntryCode()))
        {
            oClientFiledServiceDTO.setEntryCode(oClientFiledServiceDTO.getEntryCode().trim());
        }
        if(ObjectUtil.isNotEmpty( oClientFiledServiceDTO.getAvatar()))
        {
            oClientFiledServiceDTO.setAvatar(oClientFiledServiceDTO.getAvatar().trim());
        }
        QueryWrapper<YxcscClientFiledServiceEntity> oYxcscClientFiledServiceQueryWrapper = new QueryWrapper();
        oYxcscClientFiledServiceQueryWrapper.eq("channel_code", oClientFiledServiceDTO.getChannelCode().trim());
        oYxcscClientFiledServiceQueryWrapper.eq("port_code", oClientFiledServiceDTO.getPortCode().trim());
        oYxcscClientFiledServiceQueryWrapper.eq(ObjectUtil.isNotEmpty( oClientFiledServiceDTO.getShopId()),"shop_id", oClientFiledServiceDTO.getShopId().trim());
        oYxcscClientFiledServiceQueryWrapper.eq("client_id", oClientFiledServiceDTO.getUserId().trim());
        oYxcscClientFiledServiceQueryWrapper.eq("service_type", oClientFiledServiceDTO.getServiceType().trim());
        oYxcscClientFiledServiceQueryWrapper.eq(ObjectUtil.isNotEmpty( oClientFiledServiceDTO.getOrderId()),"order_id", oClientFiledServiceDTO.getOrderId());
        oYxcscClientFiledServiceQueryWrapper.eq(ObjectUtil.isNotEmpty( oClientFiledServiceDTO.getOrderState()),"order_state", oClientFiledServiceDTO.getOrderState());
        oYxcscClientFiledServiceQueryWrapper.eq(ObjectUtil.isNotEmpty( oClientFiledServiceDTO.getProductId()),"product_id", oClientFiledServiceDTO.getProductId());
        oYxcscClientFiledServiceQueryWrapper.eq(ObjectUtil.isNotEmpty( oClientFiledServiceDTO.getProductType()),"product_type", oClientFiledServiceDTO.getProductType());
        oYxcscClientFiledServiceQueryWrapper.eq(ObjectUtil.isNotEmpty( oClientFiledServiceDTO.getEntryCode()),"entry_code", oClientFiledServiceDTO.getEntryCode());
        oYxcscClientFiledServiceQueryWrapper.ne("state", 5);
        List<YxcscClientFiledServiceEntity> oYxcscClientFiledServiceList = oYxcscClientFiledServiceMapper.selectList(oYxcscClientFiledServiceQueryWrapper);
        if(!oYxcscClientFiledServiceList.isEmpty())
        {
            return BaseResult.failed("相同的服务申请，请在结束服务后再申请");
        }
        
        //YxcscClientFiledServiceDTO oYxcscClientFiledServiceDTO = new YxcscClientFiledServiceDTO();
        YxcscClientFiledServiceEntity oYxcscClientFiledServiceEntity = new YxcscClientFiledServiceEntity();
        BeanUtil.copyProperties(oClientFiledServiceDTO, oYxcscClientFiledServiceEntity);
        oYxcscClientFiledServiceEntity.setClientId(oClientFiledServiceDTO.getUserId().trim());
        oYxcscClientFiledServiceEntity.setClientName(oClientFiledServiceDTO.getNickName().trim());
        oYxcscClientFiledServiceEntity.setClientAvatar(oClientFiledServiceDTO.getAvatar());
        oYxcscClientFiledServiceEntity.setCreateTime(System.currentTimeMillis());
        oYxcscClientFiledServiceEntity.setUpdateTime(oYxcscClientFiledServiceEntity.getCreateTime());
        oYxcscClientFiledServiceEntity.setChannelId(oYxCsChannelEntity.getId().intValue());
        oYxcscClientFiledServiceEntity.setChannelName(oYxCsChannelEntity.getChannelName());
        oYxcscClientFiledServiceEntity.setPortId(oYxCsPortEntity.getId().intValue());
        oYxcscClientFiledServiceEntity.setPortName(oYxCsPortEntity.getPortName());
        oYxcscClientFiledServiceMapper.insert(oYxcscClientFiledServiceEntity);
        
        //SessionIdVO oSessionIdVO = new SessionIdVO();
        JSONObject oJSONObject = new JSONObject();
        oJSONObject.put("sessionId", oYxcscClientFiledServiceEntity.getId());
        oJSONObject.put("topic", MqttPrefixConstant.SYSTEM_CLIENT_MQTT_TOPIC_PREFIX.concat(oYxcscClientFiledServiceEntity.getId()));
        //oSessionIdVO.setSessionId(oYxcscClientFiledServiceEntity.getId());
        return BaseResult.success(oJSONObject);
    }
    /*** 
    * 客户发送聊天记录
    * @param oYxcscClientFiledServiceDTO
    * @return Integer
    **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult sendTalk(ClientSendTalkDTO oClientSendTalkDTO)
    {
        if(!oClientSendTalkDTO.getContentType().toLowerCase().equals("multitype"))
        {
            if(!oClientSendTalkDTO.getContent().toLowerCase().startsWith("http://") && !oClientSendTalkDTO.getContent().toLowerCase().startsWith("https://"))
            {
                return BaseResult.failed("该内容必须是有效的URL");
            }
        }        
        YxcscClientFiledServiceEntity oYxcscClientFiledServiceEntity = oYxcscClientFiledServiceMapper.selectById(oClientSendTalkDTO.getSessionId().trim());
        if(null == oYxcscClientFiledServiceEntity)
        {
            return BaseResult.failed("找不到对应的服务申请");
        }
        if(oYxcscClientFiledServiceEntity.getState() != 3)
        {
            return BaseResult.failed("该服务处于不能聊天状态");
        } 
        YxCsUserEntity oYxCsUserEntity = oUserMapper.selectById(oYxcscClientFiledServiceEntity.getCoustId());
        if(null == oYxCsUserEntity)
        {
            return BaseResult.failed("找不到对应的系统用户");
        }  
        oClientSendTalkDTO.setContent(oClientSendTalkDTO.getContent().trim());
        //YxCsUserWorkEntity oYxCsUserWorkEntity = oUserWorkService.getUserWorkGlobPara(oYxcscClientFiledServiceEntity.getCoustId());
        //if(null == oYxCsUserWorkEntity)
        //{
        //    return BaseResult.failed("找不到对应的客服参数信息");
        //}        
        if(oClientSendTalkDTO.getUserId().equals(oYxcscClientFiledServiceEntity.getClientId()))
        {
            YxcscServiceTalkRecordEntity oYxcscServiceTalkRecordEntity = new YxcscServiceTalkRecordEntity();
            oYxcscServiceTalkRecordEntity.setSenderId(oYxcscClientFiledServiceEntity.getClientId());
            oYxcscServiceTalkRecordEntity.setSenderName(oYxcscClientFiledServiceEntity.getClientName());
            oYxcscServiceTalkRecordEntity.setSenderType(1);
            oYxcscServiceTalkRecordEntity.setSessionId(oClientSendTalkDTO.getSessionId());
            oYxcscServiceTalkRecordEntity.setAccessServiceId(oYxcscClientFiledServiceEntity.getCurrentAccessId());
            oYxcscServiceTalkRecordEntity.setTalkInfo(oClientSendTalkDTO.getContent());
            oYxcscServiceTalkRecordEntity.setTalkInfoType(oClientSendTalkDTO.getContentType());
            oYxcscServiceTalkRecordEntity.setCreateTime(System.currentTimeMillis());
            oYxcscServiceTalkRecordMapper.insert(oYxcscServiceTalkRecordEntity);
            oIMqttProcessService.sendTalkMsgByClient(oYxcscClientFiledServiceEntity,oYxCsUserEntity,oYxcscServiceTalkRecordEntity);
            return BaseResult.success(oYxcscServiceTalkRecordEntity.getId());
        }
        else
        {
            return BaseResult.failed("发送人申请人对不上");
        }
    }
    /*** 
    * C端MQTT主题订阅结果知会服务器接口
    * @param oClientFiledDTO
    * @return BaseResult
    **/ 
    @Override
    public BaseResult subscribeTopicResult(SubscribeTopicResultDTO oSubscribeTopicResultDTO)
    {
        YxcscClientFiledServiceEntity oYxcscClientFiledServiceEntity = oYxcscClientFiledServiceMapper.selectById(oSubscribeTopicResultDTO.getSessionId());
        if(null == oYxcscClientFiledServiceEntity)
        {
            return BaseResult.failed("找不到对应的服务申请");
        } 
        if(!oYxcscClientFiledServiceEntity.getClientId().equals(oSubscribeTopicResultDTO.getUserId()))
        {
            return BaseResult.failed("没有操作权限");
        }

        List<MemberVo> list = new ArrayList();
        //正常分流
        //QueryWrapper<FlowRuleUserEntity> oFlowRuleQueryWrapper = new QueryWrapper();
        //oFlowRuleQueryWrapper.eq("channel_code", oYxcscClientFiledServiceEntity.getChannelCode()).eq("port_code", oYxcscClientFiledServiceEntity.getPortCode()).eq("service_type_code", oYxcscClientFiledServiceEntity.getServiceType());
        //oFlowRuleQueryWrapper.eq(ObjectUtil.isNotEmpty( oYxcscClientFiledServiceEntity.getEntryCode()),"rule_type_code", oYxcscClientFiledServiceEntity.getEntryCode()).or().eq(ObjectUtil.isNotEmpty( oYxcscClientFiledServiceEntity.getOrderState()),"rule_type_code", oYxcscClientFiledServiceEntity.getOrderState()).or().eq(ObjectUtil.isNotEmpty( oYxcscClientFiledServiceEntity.getProductType()),"rule_type_code", oYxcscClientFiledServiceEntity.getProductType());
        //oFlowRuleQueryWrapper.or().eq(ObjectUtil.isNotEmpty( oYxcscClientFiledServiceEntity.getProductType()),"rule_type_code", oYxcscClientFiledServiceEntity.getProductType()).or().eq(ObjectUtil.isNotEmpty( oYxcscClientFiledServiceEntity.getEntryCode()),"rule_type_code", oYxcscClientFiledServiceEntity.getEntryCode());
        //oFlowRuleQueryWrapper.or().eq(ObjectUtil.isNotEmpty( oYxcscClientFiledServiceEntity.getEntryCode()),"rule_type_code", oYxcscClientFiledServiceEntity.getEntryCode());
        //oFlowRuleQueryWrapper.or().eq(ObjectUtil.isNotEmpty( oYxcscClientFiledServiceEntity.getOrderState()),"rule_type_code", oYxcscClientFiledServiceEntity.getOrderState()).eq(ObjectUtil.isNotEmpty( oYxcscClientFiledServiceEntity.getProductType()),"rule_type_code", oYxcscClientFiledServiceEntity.getProductType()).eq(ObjectUtil.isNotEmpty( oYxcscClientFiledServiceEntity.getEntryCode()),"rule_type_code", oYxcscClientFiledServiceEntity.getEntryCode());
        //List<FlowRuleUserEntity> oListFlowRuleUserEntity = oFlowRuleUserMapper.selectList(oFlowRuleQueryWrapper);
        List<FlowRuleUserEntity> oListFlowRuleUserEntity = oFlowRuleUserMapper.getRuleUserList(oYxcscClientFiledServiceEntity);
        Long userId = Long.MAX_VALUE;
        String flockIds = "";
        MemberVo oMemberVo = null;//new MemberVo();
        HashMap<String,String> flockMap = null;// HashMap();
        //System.out.println("Long.MAX_VALUE--------------------------------------------" + Long.MAX_VALUE);
        if(!oListFlowRuleUserEntity.isEmpty())
        {
            ErrorLog.Log("sessionId:" +oYxcscClientFiledServiceEntity.getId() + "正常分流");
            for(FlowRuleUserEntity oFlowRuleUserEntity : oListFlowRuleUserEntity)
            {                
                //去掉重复用户
                if(!userId.equals(oFlowRuleUserEntity.getUserId()))
                {  
                    if(null != oMemberVo)
                    {
                        for (String key : flockMap.keySet()) {
                            if(flockIds.equals(""))
                            {
                                flockIds = key;
                            }
                            else
                            {
                                flockIds = flockIds + "," + key;
                            }
                        }
                        oMemberVo.setFlockId(flockIds);
                        list.add(oMemberVo); 
                    }
                    userId = oFlowRuleUserEntity.getUserId();
                    flockMap = new HashMap();
                    oMemberVo = new MemberVo();
                    oMemberVo.setId(oFlowRuleUserEntity.getUserId());
                    oMemberVo.setUserName(oFlowRuleUserEntity.getUserName());
                    oMemberVo.setPhone(oFlowRuleUserEntity.getMobilePhone());     
                    flockIds = "";
                }
                if(null != flockMap)
                {
                    flockMap.put(oFlowRuleUserEntity.getFlockId().toString(), oFlowRuleUserEntity.getFlockId().toString());
                }
            }
            if(null != oMemberVo)
            {
                for (String key : flockMap.keySet()) {
                    if(flockIds.equals(""))
                    {
                        flockIds = key;
                    }
                    else
                    {
                        flockIds = flockIds + "," + key;
                    }
                }
                oMemberVo.setFlockId(flockIds);
                list.add(oMemberVo); 
            }           
            oYxcscClientFiledServiceEntity.setRuleType(1);
        }
        else
        {
            //正常分流匹配不了数据
            //基础分流
            ErrorLog.Log("sessionId:" +oYxcscClientFiledServiceEntity.getId() + "基础分流");
            QueryWrapper<YxcscBaseChannelUserEntity> oYxcscBaseChannelUserQueryWrapper = new QueryWrapper();
            oYxcscBaseChannelUserQueryWrapper.eq("channel_code",oYxcscClientFiledServiceEntity.getChannelCode());
            oYxcscBaseChannelUserQueryWrapper.eq("port_code",oYxcscClientFiledServiceEntity.getPortCode());
            oYxcscBaseChannelUserQueryWrapper.eq("service_type_code",oYxcscClientFiledServiceEntity.getServiceType());
            List<YxcscBaseChannelUserEntity> oListYxcscBaseChannelUser = oYxcscBaseChannelUserMapper.selectList(oYxcscBaseChannelUserQueryWrapper);
            userId = Long.MAX_VALUE;
            for(YxcscBaseChannelUserEntity oYxcscBaseChannelUserEntity : oListYxcscBaseChannelUser)
            {
                //去掉重复用户
                if(!userId.equals(oYxcscBaseChannelUserEntity.getUserId()))
                {
                    if(null != oMemberVo)
                    {
                        for (String key : flockMap.keySet()) {
                            if(flockIds.equals(""))
                            {
                                flockIds = key;
                            }
                            else
                            {
                                flockIds = flockIds + "," + key;
                            }
                        }                        
                        oMemberVo.setFlockId(flockIds);
                        list.add(oMemberVo); 
                    }
                    userId = oYxcscBaseChannelUserEntity.getUserId();
                    flockMap = new HashMap();
                    oMemberVo = new MemberVo();
                    oMemberVo.setId(oYxcscBaseChannelUserEntity.getUserId());
                    oMemberVo.setUserName(oYxcscBaseChannelUserEntity.getUserName());
                    oMemberVo.setPhone(oYxcscBaseChannelUserEntity.getMobilePhone());
                    oMemberVo.setFlockId(oYxcscBaseChannelUserEntity.getFlockId().toString());                    
                    flockIds = "";
                }
                if(null != flockMap)
                {
                    flockMap.put(oYxcscBaseChannelUserEntity.getFlockId().toString(), oYxcscBaseChannelUserEntity.getFlockId().toString());
                }
            } 
            if(null != oMemberVo)
            {
                for (String key : flockMap.keySet()) {
                    if(flockIds.equals(""))
                    {
                        flockIds = key;
                    }
                    else
                    {
                        flockIds = flockIds + "," + key;
                    }
                }                        
                oMemberVo.setFlockId(flockIds);
                list.add(oMemberVo); 
            }
            oYxcscClientFiledServiceEntity.setRuleType(0);
        } 
        if(oYxcscClientFiledServiceEntity.getState()>=2)
        {
            return BaseResult.success(list);
        }
        oYxcscClientFiledServiceEntity.setFlockId(flockIds);
        UpdateWrapper<YxcscClientFiledServiceEntity> oUpdateWrapper = new UpdateWrapper();
        oUpdateWrapper.eq("session_id", oSubscribeTopicResultDTO.getSessionId());
        oUpdateWrapper.set("state", 2);
        oUpdateWrapper.set("rule_type", oYxcscClientFiledServiceEntity.getRuleType());
        oUpdateWrapper.set("flock_id", flockIds);
        int i = oYxcscClientFiledServiceMapper.update(null, oUpdateWrapper);
        if(i == 1)
        {
            return oIMqttProcessService.sendSystemMsgByClientFiled(oYxcscClientFiledServiceEntity,list);
            //return BaseResult.success();
        }
        else
        {
            return BaseResult.failed("知会失败");
        }
    }
    /*** 
    * 客户申请完成某个服务接口
    * @param userId
    * @return MqttServerInforVO
    **/
    @Override
    public BaseResult clientFinishService(String userId,String sessionId)
    {
        YxcscClientFiledServiceEntity oYxcscClientFiledServiceEntity = oYxcscClientFiledServiceMapper.selectById(sessionId);
        if(null == oYxcscClientFiledServiceEntity)
        {
            return BaseResult.failed("找不到对应的服务申请");
        } 
        if(StrUtil.isNotBlank(oYxcscClientFiledServiceEntity.getClientId()))
        {
            if(!oYxcscClientFiledServiceEntity.getClientId().equals(userId))
            {
                return BaseResult.failed("没有操作权限");
            }
        }
        YxcscCustomerAccessServiceEntity oCustomerAccessServiceOld = oYxcscCustomerAccessServiceMapper.selectById(oYxcscClientFiledServiceEntity.getCurrentAccessId());
        if(null == oCustomerAccessServiceOld)
        {
            return BaseResult.failed("找不到当前处理人");
        }  
        oCustomerAccessServiceOld.setUpdateTime(oYxcscClientFiledServiceEntity.getUpdateTime());
        oCustomerAccessServiceOld.setStatus(1);
        oYxcscClientFiledServiceEntity.setState(5);
        oYxcscClientFiledServiceEntity.setUpdateTime(System.currentTimeMillis());
        oYxcscClientFiledServiceMapper.updateById(oYxcscClientFiledServiceEntity);
        oYxcscCustomerAccessServiceMapper.updateById(oCustomerAccessServiceOld);
        oIMqttProcessService.serviceScore(oYxcscClientFiledServiceEntity);
        return BaseResult.success();
    }
    /**
     * 客户对服务的评分接口
     * @param ClientSendTalkDTO 会话内容
     * @return 
     */
    @Override
    public BaseResult<String> serviceScore(ClientScoreDTO oClientScoreDTO)
    {
        YxcscClientFiledServiceEntity oYxcscClientFiledServiceEntity = oYxcscClientFiledServiceMapper.selectById(oClientScoreDTO.getSessionId());
        if(null == oYxcscClientFiledServiceEntity)
        {
            return BaseResult.failed("找不到对应的服务申请");
        } 
        if(!oYxcscClientFiledServiceEntity.getClientId().equals(oClientScoreDTO.getUserId()))
        {
            return BaseResult.failed("没有操作权限");
        }        
        UpdateWrapper<YxcscClientFiledServiceEntity> oUpdateWrapper = new UpdateWrapper();
        oUpdateWrapper.eq("session_id", oClientScoreDTO.getSessionId());
        oUpdateWrapper.set("evaluate", oClientScoreDTO.getScore());
        
        UpdateWrapper<YxcscCustomerAccessServiceEntity> oCustomerAccessUpdateWrapper = new UpdateWrapper();
        oCustomerAccessUpdateWrapper.eq("access_id", oYxcscClientFiledServiceEntity.getCurrentAccessId());
        oCustomerAccessUpdateWrapper.set("evaluate", oClientScoreDTO.getScore());
        oYxcscClientFiledServiceMapper.update(null, oUpdateWrapper);
        oYxcscCustomerAccessServiceMapper.update(null, oCustomerAccessUpdateWrapper);
        return BaseResult.success("谢谢参与");
    }
    /**
     * 获取常见问题帮助文档列表接口
     * @param oClientHelpDocuListDTO 助文档列表
     * @return 
     */
    @Override
    public BaseResult recDocuList(ClientHelpDocuListDTO oClientHelpDocuListDTO)
    {
        Page<YxCsProblemLibEntity> pageParams = new Page<>(oClientHelpDocuListDTO.getPage(),oClientHelpDocuListDTO.getSize());
        QueryWrapper<YxCsProblemLibEntity> oYxCsProblemLibQueryWrapper = new QueryWrapper();
        //oYxCsProblemLibQueryWrapper.eq(ObjectUtil.isNotEmpty(oYxCsProblemLibEntity.getProblemLibId()),"problem_lib_id",oYxCsProblemLibEntity.getProblemLibId());
        oYxCsProblemLibQueryWrapper.eq(ObjectUtil.isNotEmpty(oClientHelpDocuListDTO.getChannelCode()),"channel_code",oClientHelpDocuListDTO.getChannelCode());
        //int iCount = oPrcMapper.selectCount(oYxCsProblemLibQueryWrapper);
        Page<YxCsProblemLibEntity> oPage = oPrcMapper.selectPage(pageParams, oYxCsProblemLibQueryWrapper);        
        List<YxCsProblemLibEntity> listProblemLib = oPage.getRecords();
        JSONObject oJSONObject = new JSONObject();
        oJSONObject.put("currenPage", oPage.getCurrent());
        oJSONObject.put("size", oPage.getSize());
        oJSONObject.put("pageCount", oPage.getPages());
        oJSONObject.put("record", oPage.getTotal());
        JSONArray oJSONArray = new JSONArray();
        for(YxCsProblemLibEntity oYxCsProblemLibEntityInner : listProblemLib)
        {
            JSONObject oJSONObjectInner = new JSONObject();
            oJSONObjectInner.put("docuId", oYxCsProblemLibEntityInner.getProblemLibId());
            oJSONObjectInner.put("docuType", "multitype");
            oJSONObjectInner.put("docuDes", oYxCsProblemLibEntityInner.getProDes());
            oJSONArray.add(oJSONObjectInner);
        }
        oJSONObject.put("list", oJSONArray);
        return BaseResult.success(oJSONObject);
    }
    /**
     * 获取常见问题帮助文档详情接口
     * @param oClientHelpDocuDTO 会话内容
     * @return 
     */
    @Override
    public BaseResult recDocuDedail(ClientHelpDocuDTO oClientHelpDocuDTO)
    {
        YxCsProblemLibEntity oYxCsProblemLibEntity = oPrcMapper.selectById(Long.valueOf(oClientHelpDocuDTO.getDocuId()));
        if(null != oYxCsProblemLibEntity)
        {
            JSONObject oJSONObject = new JSONObject();
            oJSONObject.put("docuId", oYxCsProblemLibEntity.getProblemLibId());
            oJSONObject.put("docuType", "multitype");
            oJSONObject.put("docuContent",oYxCsProblemLibEntity.getReplyDes());
            return BaseResult.success(oJSONObject);
        }
        return BaseResult.failed("找不到对应Id的文档");
    }
    
    /*** 
    *客户撤回/删除聊天记录接口
    * @param customerId 客服Id
    * @param recordId 聊天记录Id
    * @param operationState 操作状态:0正常的消息,1删除的消息,2撤回的消息
    * @return BaseResult
    **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult clientRevokeServiceTalkRecord(String clientId,Long recordId,Integer operationState)
    {
        if(operationState != 1  && operationState != 2)
        {
            return BaseResult.failed("operationState只能等于1[删除]或2[撤回]");
        }
        YxcscServiceTalkRecordEntity oYxcscServiceTalkRecordEntity = oYxcscServiceTalkRecordMapper.selectById(recordId);
        if(null == oYxcscServiceTalkRecordEntity)
        {
            return BaseResult.failed("找不到聊天记录");
        }
        if((System.currentTimeMillis() - oYxcscServiceTalkRecordEntity.getCreateTime()) > 12000)
        {
            return BaseResult.failed("聊天记录创建时间超过当前时间两分钟，不能撤回");
        }
        if(!oYxcscServiceTalkRecordEntity.getSenderId().equals(clientId))
        {
            return BaseResult.failed("没有撤回/删除聊天记录权限，不能撤回");
        }
        YxcscClientFiledServiceEntity oYxcscClientFiledServiceEntity = oYxcscClientFiledServiceMapper.selectById(oYxcscServiceTalkRecordEntity.getSessionId());
        oYxcscServiceTalkRecordEntity.setOperationState(operationState);
        oYxcscServiceTalkRecordEntity.setOperationTime(System.currentTimeMillis());
        oYxcscServiceTalkRecordMapper.updateById(oYxcscServiceTalkRecordEntity);
        if(operationState == 2)
        {
            oIMqttProcessService.clientRevokeServiceTalkRecord(recordId, oYxcscClientFiledServiceEntity.getCoustId());
        }
        return BaseResult.success();
    }    
}